package com.ad.services;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.ad.models.City;
import com.ad.models.Weather;
import com.ad.system.Common;
import com.ad.system.HttpClientWrapper;
import com.ad.system.SystemVariable;

public class HttpService implements IHttpService {

	private static Logger log = Logger.getLogger(HttpService.class);

	// /**
	// * 通过http://www.linkwan.com/gb/broadmeter/VisitorInfo/systeminfo.asp?
	// * OnlyAddress=yes查询ip及所在地
	// */
	// public City getClientSite() {
	// String url =
	// "http://www.linkwan.com/gb/broadmeter/VisitorInfo/systeminfo.asp?OnlyAddress=yes";
	// String rawCityInfo = HttpClientWrapper.httpGet(url, "");
	// return parseRawCityInfo(rawCityInfo);
	// }

	// /**
	// * 通过 http://www.linkwan.com/gb/broadmeter/VisitorInfo
	// * /systeminfo.asp?OnlyAddress=yes查询
	// */
	// public City getClientSite(HttpServletRequest request) {
	// return this.getClientSite();
	// /*
	// * String ip = getClientIp(request); City site = new City(); // 如果查询不到ip
	// * if (Common.isEmpty(ip)) { return null; } site.setIp(ip); // 尝试三次 int
	// * tryTimes = 3; LocationResult location = null;
	// *
	// *
	// * do { //发现bug，此方法有可能造成网站lag //location = this.findLocation(ip,
	// * request);
	// *
	// * } while (location == null && tryTimes-- > 0);
	// *
	// * // 如果仍然是null，用另外一种方法取得城市 if (location == null) {
	// * //log.info("Guzz查询城市三次尝试后仍然无法取得，转用IHttpServie.getClientSite()方法。");
	// * return this.getClientSite(); }
	// *
	// * site.setProvince(location.areaName); String city = location.cityName;
	// * if (city.contains("省")) { String rawCity =
	// * location.cityName.split("省")[1]; site.setCity(rawCity.substring(0,
	// * rawCity.length() - 1)); } else { site.setCity(location.areaName); }
	// * return site;
	// */
	// // return getClientCity();
	// }

	/**
	 * 查询客户端ip
	 */
	public String getClientIp(HttpServletRequest request) {
		String ip = Common.getIpAddr(request);
		if ("127.0.0.1".equals(ip)) {
			ip = parseClinetIPFromURL();
		}
		return ip;
	}

	public String getWeather(HttpServletRequest request, String cityInfo) {

		City site = parseRawCityInfo(cityInfo);

		String weather = "";
		if (site != null) {
			int cutPlace = SystemVariable.CITY_CODE.indexOf(site.getCity());
			if (cutPlace > 0) {
				String sub = SystemVariable.CITY_CODE.substring(0, cutPlace);
				String code = Common.splitMatchLast("',", "=>", sub);
				// 旧网址"http://www.tianqi123.com/small_page/chengshi_"
				String url = "http://www.tianqi123.com/tianqi/chengshi_" + code
						+ ".html";

				weather = site.getWhole() + "&nbsp;&nbsp;" + getWeather(url);
			}
		}
		return weather;
	}

	public String getWeather(String url) {
		// if (Common.isEmpty(url)) {
		// return "";
		// }
		// String rawHtml = HttpClientWrapper.httpGet(url, "gb2312");
		// StringBuffer resultBuffer = new StringBuffer();
		//
		// int itemIndex = 3;
		// Calendar calendar = Calendar.getInstance();
		// int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
		// if (hourOfDay >= 18 && hourOfDay <= 23) {
		// itemIndex = 4;
		// } else if (hourOfDay >= 0 && hourOfDay <= 9) {
		// itemIndex = 5;
		// }
		//
		// try {
		// String[] raw = rawHtml.split("id=tq" + itemIndex + ">")[1]
		// .split("id=tq" + itemIndex + 1 + ">")[0].split("</td>");
		// String weatherIconUrl = "";
		// for (int i = 0; i < 3; i++) {
		// int start = raw[i].lastIndexOf(">");
		// int end = raw[i].length();
		// if (i == 1) {
		// weatherIconUrl = raw[i].substring(0, start).split("src=")[1]
		// .split(".gif")[0];
		// weatherIconUrl = weatherIconUrl + ".gif";
		// resultBuffer.append(weatherIcon(weatherIconUrl))
		// .append(" ");
		// }
		// resultBuffer.append(raw[i].substring(start + 1, end)).append(
		// " ");
		// }
		// } catch (Exception e) {
		// log.info("when extracting weather html code, get exception:"
		// + e.getMessage());
		// e.printStackTrace();
		// return "";
		// }
		//
		// return resultBuffer.toString().trim();

		if (Common.isEmpty(url)) {
			return "";
		}
		String rawHtml = HttpClientWrapper.httpGet(url, "gb2312");

		Weather wth = new Weather(rawHtml);
		try {
			return wth.getWeatherHTMLCode();
			// resultBuffer.append(raw[i].substring(start + 1,
			// end)).append(" ");
		} catch (Exception e) {
			log.info("when extracting weather html code, get exception:"
					+ e.getMessage());
			e.printStackTrace();
			wth.setItem(wth.getWeatherList().get(1));
			return wth.getWeatherHTMLCode();
		}

	}

	public City getClientCity(String rawCityInfo) {
		return parseRawCityInfo(rawCityInfo);
	}

	private String parseClinetIPFromURL() {
		String url = "http://www.linkwan.com/gb/broadmeter/VisitorInfo/systeminfo.asp?OnlyAddress=yes";
		String rawCityInfo = HttpClientWrapper.httpGet(url, "");
		String[] raw = rawCityInfo.split("来自");
		String ip = Common.splitMatchFirst(">", "<", raw[0]);
		return ip;
	}

	private City parseRawCityInfo(String rawCityInfo) {
		if (Common.isEmpty(rawCityInfo)) {
			return null;
		}

		City site = new City(rawCityInfo);
		log.info("城市:" + site.getProvince() + site.getCity());
		return site;

	}
}
